package com.bookstore.servlet;

import com.bookstore.pojo.Book;
import com.bookstore.pojo.Cart;
import com.bookstore.pojo.CartItem;
import com.bookstore.services.BookService;
import com.bookstore.services.Impl.BookServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "CartServlet", value = "/CartServlet")
public class CartServlet extends BaseServlet {

    BookService bookService=new BookServiceImpl();
    private Gson gson=new Gson();

    protected void addBookToCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String readLine = request.getReader().readLine();
        System.out.println(readLine);
        Book book = gson.fromJson(readLine, Book.class);
        System.out.println("购物"+book);
        HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart==null){
            cart=new Cart();
            session.setAttribute("cart",cart);
        }
        session.setMaxInactiveInterval(60*7);
        Book one = bookService.getOne(book);
        cart.addBookToCart(one);
        System.out.println(cart);
        String toJson = gson.toJson(cart);
        response.getWriter().write(toJson);
    }


    protected void deleteItem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        cart.deleteItem(id);
    }

    protected void clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart==null){
            cart=new Cart();
            session.setAttribute("cart",cart);
        }
        cart.clear();
    }

    protected void getCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if(cart!=null){
            List<CartItem> allItems = cart.getAllItems();
            String toJson = gson.toJson(allItems);
            response.getWriter().write(toJson);
        }
    }
}
